package com.ztom.top100;

import java.util.LinkedList;
import java.util.Queue;

/**
 * 合并二叉树
 * <p>
 * https://leetcode-cn.com/problems/merge-two-binary-trees/
 *
 * @author ZhangTao
 */
public class Code97MergeTrees {

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public TreeNode mergeTrees(TreeNode root1, TreeNode root2) {
        if (root1 == null) {
            return root2;
        }
        if (root2 == null) {
            return root1;
        }

        TreeNode node = new TreeNode(root1.val + root2.val);
        node.left = mergeTrees(root1.left, root2.left);
        node.right = mergeTrees(root1.right, root2.right);
        return node;
    }

    public TreeNode mergeTrees1(TreeNode root1, TreeNode root2) {
        if (root1 == null) {
            return root2;
        }
        if (root2 == null) {
            return root1;
        }

        Queue<TreeNode> queue = new LinkedList<>();
        Queue<TreeNode> q1 = new LinkedList<>();
        Queue<TreeNode> q2 = new LinkedList<>();
        // 根节点
        TreeNode root = new TreeNode(root1.val + root2.val);
        queue.offer(root);
        q1.offer(root1);
        q2.offer(root2);

        while (!q1.isEmpty() && !q2.isEmpty()) {
            TreeNode node = queue.poll();
            TreeNode node1 = q1.poll();
            TreeNode node2 = q2.poll();
            if (node1.left != null && node2.left != null) {
                node.left = new TreeNode(node1.left.val + node2.left.val);
                queue.offer(node.left);
                q1.offer(node1.left);
                q2.offer(node2.left);
            } else if (node1.left != null) {
                node.left = node1.left;
            } else if (node2.left != null) {
                node.left = node2.left;
            }
            if (node1.right != null && node2.right != null) {
                node.right = new TreeNode(node1.right.val + node2.right.val);
                queue.offer(node.right);
                q1.offer(node1.right);
                q2.offer(node2.right);
            } else if (node1.right != null) {
                node.right = node1.right;
            } else if (node2.right != null) {
                node.right = node2.right;
            }
        }

        return root;
    }
}
